package io.renren.modules.front.base;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;

import io.renren.util.SendSMSByWebUtils;

/**
 * <p>
 * 图片验证码和短信验证码相关的BaseController
 * </p>
 *
 * @author yuxiaobin
 * @date 2017/8/21
 */
public abstract class ImageCodeSmsBaseController extends FrontBaseController{

    protected static final String REG_PARAM_VCODE = "vcode";//图片验证码参数名
    protected static final String REG_PARAM_MOBILE = "mobile";//手机号参数名
    protected static final String REG_PARAM_SMSCODE = "smscode";//手机短信验证码参数名
    protected static final String REG_PARAM_OPENID = "openId";//微信用户标识参数名

    @Autowired(required = false)
    protected RedisTemplate<String, String> redisTemplate;


    //核对验证码是否正确
    protected boolean checkImgCodesWithRefresh(String imgCode) throws IOException {
        boolean isRight = false;
        if (StringUtils.isNotBlank(imgCode)) {
            Object imgCode_session = request.getSession().getAttribute("capText");
            request.getSession().removeAttribute("capText");
            if (imgCode_session != null && imgCode_session.toString().equalsIgnoreCase(imgCode)){
                isRight = true;
            }
        }
        return isRight;
    }

    protected String getImgCode(){
        return (String) request.getSession().getAttribute("capText");
    }

    protected void deleteImgCode(){
        request.getSession().removeAttribute("capText");
    }

    protected void generateAndWriteImgCode(){

        try (ServletOutputStream out = response.getOutputStream();){
            Map<String,Object> map=genPic();
            Set<Map.Entry<String, Object>> entrySet = map.entrySet();
            BufferedImage bi=null;
            String capText="";
            for (Map.Entry<String, Object> entry : entrySet) {
                String key = entry.getKey();
                if(key.equalsIgnoreCase("img")){
                    bi=(BufferedImage) entry.getValue();
                }else{
                    capText=(String) entry.getValue();
                }
            }
            request.getSession().setAttribute("capText", capText);
            System.out.println("imgcode="+capText);
            ImageIO.write(bi, "jpg", out);//图形流输出验证码
        } catch (IOException e) {
            System.out.println("写验证码图片失败");
            e.printStackTrace();
        }
    }

    protected ThreadLocal<String> validationError = new ThreadLocal<>();

    private Map<String,Object> genPic(){
        // create the text for the image
        Properties props = new Properties();
        Producer kaptchaProducer = null;
        ImageIO.setUseCache(false);
        props.put("kaptcha.border", "no");
        props.put("kaptcha.textproducer.font.color", "black");
        props.put("kaptcha.textproducer.char.space", "5");//这三行控制验证码的格式
        Config config = new Config(props);
        kaptchaProducer = config.getProducerImpl();
        String capText = kaptchaProducer.createText();
        BufferedImage bi = kaptchaProducer.createImage(capText);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("img",bi);
        map.put("text",capText);
        return map;
    }

    /**
     * 生成短信验证码
     */
    protected String generateSmsCode(){
        Random rand = new Random();
        String str = "";
        for (int i = 0; i < 4; i++){
            str = str + rand.nextInt(10);
        }
        return str;
    }

    protected boolean checkMobileAllow2SendSms(String mobile){
        /*if(!mobileSmsLimitService.checkMobileRegisterAllowSms(mobile)){
            logger.info("checkMobileRegisterAllowSms=false, which means sent to this mobile in 2 minutes, check blocked");
            validationError.set("验证码已发送，如未收到，请在2分钟后再尝试");
            return false;
        }else{
            if(mobileSmsLimitService.checkMobileExceedDailyLimit(mobile)){
                logger.info("checkMobileExceedDailyLimit=true, which means count of sms sent to same mobile exceed to max:[sms.daily.limit] or 10 by default, not allow send in 24 hours");
                validationError.set("短信验证码发送已达上限，请明日再试");
                return false;
            }
            mobileSmsLimitService.recordMobileRegisterSendSms(mobile);
            return true;
        }*/
        return true;
    }

    protected Object sendSms(JSONObject result, String mobileNum){
        String smsCode = generateSmsCode();
        logger.info("****mobile=["+mobileNum+"] request smscode=["+smsCode+"] for register");
        if(SendSMSByWebUtils.sendVerifyCodeMsgByTemplate(mobileNum, smsCode, getLocale())){
            result.put(MSG, "success");
//            smsUtil4Redis.saveSms4MobileRegister(mobileNum, smsCode);
//            mobileSmsLimitService.trackMobileSms4Daily(mobileNum);
            return getSuccessResult(result);
        }else{
            logger.error("******************SMS API error, failed to send sms code to mobile["+mobileNum+"]*************");
            result.put(VERROR, "验证码已发送，如未收到，请在2分钟后再尝试");
            result.put(RELOAD, false);
            return getInvalidParamResult(result);
        }
    }

    private String getLocale(){
        return "CN";//TODO
    }
}
